/**
 * Copyright 2009 University of  Washington
 * This code is released under the GPL version 3 - with a copy of the license included
 * @author Maya Hao Li
 *
 */
package seedpod.webapp.controller;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import seedpod.util.Util;
import seedpod.webapp.LimsContext;
import seedpod.webapp.LimsSession;
import seedpod.webapp.Seedpod;

public class AuthenticationFilter implements Filter {

	private HttpServletRequest _request;

	private LimsSession _limsSession;

	private static boolean loginTest = false;
	
	public void destroy() {
	// TODO Auto-generated method stub
	}

	public void init( FilterConfig filterConfig ) throws ServletException {
		
	}

	public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException,
			ServletException {
		if ( request instanceof HttpServletRequest ) {
			_request = (HttpServletRequest)request;
			_limsSession = new LimsSession( _request );
			_limsSession.pushRequestedURL();

			String loginUrl = LimsContext.getLoginUrl();
			loginUrl = Util.getAbsoluteURL( Seedpod.getWebappUrlRoot(), loginUrl);
			
			if ( !_limsSession.isActive() ) {
				System.err.println("authenticationFilter: _limsSession timed out");
				Util.jsRedirect( loginUrl, request, response);
			}
			else if ( loginTest || !_limsSession.isAuthenticated() )  {
				System.err.println("authenticationFilter: _limsSession is not authenticated");
				Util.redirect( loginUrl, request, response );
			}
			else {
				System.err.println( "authenticationFilter passed");
				chain.doFilter( request, response );
			}
		}
	}
}
